
package w83a.w83aManager;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import sun.misc.BASE64Encoder;
import w83a.Thread.W83ANotificacionThread;
import w83a.w83aUtilidadesComunes.W83ABase64;
import w83a.w83aUtilidadesComunes.W83ADateUtils;
import w83a.w83aUtilidadesComunes.W83AProperties;
import w83a.w83aUtilidadesComunes.W83AStringUtil;
import w83a.w83aUtilidadesComunes.W83AWebServiceCall;
import w83a.w83aUtilidadesComunes.W83aClsTrazas;
import w83a.w83aUtilidadesComunes.W83aException;


public class W83AEjGvDocumento implements Serializable{//NOPMD

	private static final long serialVersionUID = 1L;	
	
	public static String obtenerFirmasimple(String sessionToken, String certificateID,String txt) {
		String result = "";
		try {
			W83aClsTrazas.trazaError(null, " **** 1 obtenerFirmasimple", new Exception() );//NOPMD
			
			if(W83AProperties.getProperty("w83a","dokusi.firma.servidor.ACTIVE").equals("true")){
				String jpdMethod = "createSimplSignByteArray";
				W83aClsTrazas.trazaError(null, " **** 2 jpdMethod", new Exception() );//NOPMD

				BufferedWriter out = new BufferedWriter(new FileWriter(W83AProperties.getProperty("w83a", "file.out")+"obtenerFirma.txt",true));
				out.write("\r\n\r\n"+"textopreparado=>"+txt+"$$$");
				
				
				
				MessageFactory mfactory = MessageFactory.newInstance();
				SOAPMessage message = mfactory.createMessage();
				SOAPPart soapPart = message.getSOAPPart();
				SOAPEnvelope envelope = soapPart.getEnvelope();
				SOAPBody body = envelope.getBody();
				Name name = envelope.createName(jpdMethod, "",
						"http://www.openuri.org/");
				SOAPBodyElement element = body.addBodyElement(name);
				SOAPElement symbol = element.addChildElement(envelope
						.createName("sessionToken"));
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("certificateID"));
				symbol.addTextNode(certificateID);
				symbol = element.addChildElement(envelope.createName("simplDocums"));
				symbol.addTextNode(txt);
	
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				SOAPConnection con = factory.createConnection();
				
				String url = W83AProperties.getProperty("w83a","url.ws.Q99vDigitalSignatureJWS");
				W83aClsTrazas.trazaError(null, " **** 20 url: "+url, new Exception() );//NOPMD
				if (log.isLoggable(Level.INFO)){
					log.info("sessionToken="+sessionToken);
					log.info("certificateID="+certificateID);
					log.info("txt codigicado base64 para la firma"+txt);
				}
	
				SOAPMessage responseWebServ = con.call(message, url);
				result = W83AWebServiceCall.getResultado(responseWebServ);
				W83aClsTrazas.trazaError(null, " **** result: "+result , new Exception() );//NOPMD
				if (result.startsWith("Fallo:")){
					result="";
				}
				
				out.write("RESULTADO:" + result);
				
				 out.close();
			}else{
				result = "Hola Mundo";
			}
			if (log.isLoggable(Level.INFO)){
				log.info("Result obtener firma simple servidor-->" + result);
			}
			
			return result;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	
	public static String obtenerJustificante(String numRegES, String sessionToken) {
		String result = "";
		try {
			
			
				//String jpdMethod = "getRegistryReceipt";
				String jpdMethod = "getRegistryReceiptST";
				
				MessageFactory mfactory = MessageFactory.newInstance();
				
				SOAPMessage message = mfactory.createMessage();
				
				SOAPPart soapPart = message.getSOAPPart();
				
				SOAPEnvelope envelope = soapPart.getEnvelope();
				
				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
				"http://www.openuri.org/");
				
				SOAPBodyElement element = body.addBodyElement(name);
				
				SOAPElement symbol = element.addChildElement(envelope
						.createName("sSessionToken"));
				
				symbol.addTextNode(sessionToken);
				
				symbol = element.addChildElement(envelope
						.createName("sRegistryNumber"));
				
				symbol.addTextNode(numRegES);
				
				
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
			
				String url = W83AProperties.getProperty("w83a","url.ws.justificante");
				
				if (log.isLoggable(Level.INFO)){
					log.info("numRegES="+numRegES);
				
				}
				
				
				SOAPMessage responseWebServ = con.call(message, url);
				
				result = W83AWebServiceCall.getResultado(responseWebServ);
				if (log.isLoggable(Level.INFO)){
					log.info("Result -->" + result);
				}
				
				String firma=W83AStringUtil.obtenerPatronInicioFinSinComent2(result, "dsig:X509IssuerName");
			
			if (log.isLoggable(Level.INFO)){
				log.info("Result obtener justificante-->" + firma);
			}
		
			
			
			return firma;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	

	
	public static String generarNotificacion(String sessionToken, String tareaNotificar) throws W83aException{
		String result = "";
		
		W83aClsTrazas.trazaDebug(null, "INICIO generarNotificacion");
		
		try {
            Date fecha=new Date();
            String sfecha=W83ADateUtils.dateTimeToString(fecha);
          
            //Guardamos en un txt en datos los detalles de la llamada a WS
    		BufferedWriter out = new BufferedWriter(new FileWriter(W83AProperties.getProperty("w83a", "file.out")+"generarNotificacion.txt",true));
    		out.write(sfecha+"\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"tareaNotificar=>"+tareaNotificar+"\r\n\r\n");
    		out.close();
						
			if(W83AProperties.getProperty("w83a","notificar.crear.ACTIVE").equals("true")){
				
				//Metodo 
				String jpdMethod = W83AProperties.getProperty("w83a","notificacion.procedure.crear");
			
				MessageFactory mfactory = MessageFactory.newInstance();
				SOAPMessage message = mfactory.createMessage();
				SOAPPart soapPart = message.getSOAPPart();
				SOAPEnvelope envelope = soapPart.getEnvelope();
				SOAPBody body = envelope.getBody();
				Name name = envelope.createName(jpdMethod, "","http://www.openuri.org/");
				
				//Aņadimos los parametros de la llamada al WS
				SOAPBodyElement element = body.addBodyElement(name);
				SOAPElement symbol = element.addChildElement(envelope.createName("sessionToken"));
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("tareaNotificar"));
				symbol.addTextNode(tareaNotificar);
				
				
								
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				SOAPConnection con = factory.createConnection();
				String url = W83AProperties.getProperty("w83a","url.ws.crearNotificacion");
				
				
				if (log.isLoggable(Level.INFO)){
					log.info("generarNotificacion");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				
				W83aClsTrazas.trazaDebug(null, "generarNotificacion->Metodo="+jpdMethod+" url="+url);
				W83aClsTrazas.trazaDebug(null, "generarNotificacion->message="+message);
				
				
				SOAPMessage responseWebServ = con.call(message, url);
				result = W83AWebServiceCall.getResultado(responseWebServ);
				
		       //Guardamos en un txt en datos los detalles de larespues a la  llamada a WS
	    		BufferedWriter outResult = new BufferedWriter(new FileWriter(W83AProperties.getProperty("w83a", "file.out")+"generarNotificacionResult.txt",true));
	    		outResult.write(sfecha+"\r\n\r\n"+"result=>"+result+"\r\n\r\n");
	    		outResult.close();
				
				W83aClsTrazas.trazaDebug(null, " @@@@@@  24 generarNotificacion->result: " +result );
			
			}
			
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				log.info("tareaNotificar="+tareaNotificar);
			}
		
			W83aClsTrazas.trazaDebug(null, "FIN generarNotificacion");
			return result;				

			
		} catch (IOException ioe) {
			return "";
		} catch (Exception ex) {
			return "";
		}

	}
	public static String publicarNotificacion(String sessionToken, String sUnsignedNotification,String bytesFirma) {
		String result = "";

		try {
			W83aClsTrazas.trazaDebug(null, "===> 1 en publicarNotificacion");
	        Date fecha=new Date();
	        String sfecha=W83ADateUtils.dateTimeToString(fecha);
	           
	        //Guardamos en un txt en datos los detalles de la llamada a WS
	    	BufferedWriter out = new BufferedWriter(new FileWriter(W83AProperties.getProperty("w83a", "file.out")+"publicarNotificacion.txt",true));
	        out.write(sfecha+"\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"tareaNotificar=>"+sUnsignedNotification+"\r\n\r\n"+"bytesNotification=>"+bytesFirma+"\r\n\r\n");
	        out.close();
				
			if(W83AProperties.getProperty("w83a","notificar.crear.ACTIVE").equals("true")){
				
				//Metodo publicar
				String jpdMethod = W83AProperties.getProperty("w83a","notificacion.procedure.publicar");
				
				MessageFactory mfactory = MessageFactory.newInstance();
				SOAPMessage message = mfactory.createMessage();
				SOAPPart soapPart = message.getSOAPPart();
				SOAPEnvelope envelope = soapPart.getEnvelope();
				SOAPBody body = envelope.getBody();
				Name name = envelope.createName(jpdMethod, "","http://www.openuri.org/");
				
				
				//Aņadimos los parametros de la llamada al WS
				SOAPBodyElement element = body.addBodyElement(name);
				SOAPElement symbol = element.addChildElement(envelope.createName("sSessionToken"));
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("sUnsignedNotification"));
				symbol.addTextNode(sUnsignedNotification);
				//symbol.addTextNode(base64sUnsignedNotification);
				symbol = element.addChildElement(envelope.createName("bytesNotification"));
				symbol.addTextNode(bytesFirma);
			
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				SOAPConnection con = factory.createConnection();
				String url = W83AProperties.getProperty("w83a","url.ws.crearNotificacion");
				
				
				if (log.isLoggable(Level.INFO)){
					log.info("publicarNotificacion");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				
				
				W83aClsTrazas.trazaDebug(null, "===> 26 ");
				if (log.isLoggable(Level.INFO)){
					log.info("***message="+message);
				}
				
				W83aClsTrazas.trazaDebug(null, "publicarNotificacion->Metodo="+jpdMethod+" url="+url);
				W83aClsTrazas.trazaDebug(null, "publicarNotificacion->message="+message);
				
				//LLAMADA AL WS
				SOAPMessage responseWebServ = con.call(message, url);
				W83aClsTrazas.trazaDebug(null, "===> 27 publicarNotificacion responseWebServ:"+responseWebServ);
				
				//RESULTADO
				result = W83AWebServiceCall.getResultado(responseWebServ);
				W83aClsTrazas.trazaDebug(null, "===> 28 publicarNotificacion result:"+result);
			}else{
				result = "";
			}
		
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				log.info("sUnsignedNotification="+sUnsignedNotification);
				log.info("bytesNotification="+bytesFirma);
				log.info("-->" + result);
			}
		
			if (result.startsWith("Fallo")){
				result="";
			}
		
			
			
		} catch (IOException ioe) {
			W83aClsTrazas.trazaError(null, "===> IOException", ioe);
			result="";
			
		} catch (Exception ex) {
			W83aClsTrazas.trazaError(null, "===> Exception", ex);
			result="";
		}
		
		W83aClsTrazas.trazaDebug(null, "FIN publicarNotificacion");
		return result;
	}
	
	public static String comprobarFirma(String sessionToken, String documento, String bytesFirma) {
		String result = "";

		try {
			W83aClsTrazas.trazaDebug(null, "===> 1 en comprobarfirma");
			
			BufferedWriter out = new BufferedWriter(new FileWriter(W83AProperties.getProperty("w83a", "file.out")+"comprobarFirma.txt",true));
    		 out.write("\r\n\r\n"+"sessionToken=>"+sessionToken+"\r\n\r\n"+"documento=>"+documento+"\r\n\r\n"+"bytesFirma"+bytesFirma+"\r\n\r\n");
          out.close();
			
				String jpdMethod = "verifySimplelSignByteArray";
				
				MessageFactory mfactory = MessageFactory.newInstance();
				
				SOAPMessage message = mfactory.createMessage();
				
				SOAPPart soapPart = message.getSOAPPart();
				
				SOAPEnvelope envelope = soapPart.getEnvelope();
				
				SOAPBody body = envelope.getBody();
				
				Name name = envelope.createName(jpdMethod, "",
				"http://www.openuri.org/");
				
			
				SOAPBodyElement element = body.addBodyElement(name);
				

				SOAPElement symbol = element.addChildElement(envelope.createName("sSecurityToken"));
				
				
				symbol.addTextNode(sessionToken);
				symbol = element.addChildElement(envelope.createName("simpleSign"));
				
				symbol.addTextNode(bytesFirma);
				
				
				symbol = element.addChildElement(envelope.createName("documents"));
				
				symbol.addTextNode(documento);
				
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				
				SOAPConnection con = factory.createConnection();
				
				String url = W83AProperties.getProperty("w83a",
				"url.ws.Q99vDigitalSignatureJWS");
				
				
				if (log.isLoggable(Level.INFO)){
					log.info("comprobarFirma");
					log.info("Metodo="+jpdMethod);
					log.info("url="+url);
				}
				W83aClsTrazas.trazaDebug(null, "===> 26 ");
				if (log.isLoggable(Level.INFO)){
					log.info("***message="+message);
				}
				SOAPMessage responseWebServ = con.call(message, url);
				W83aClsTrazas.trazaDebug(null, "===> 27 responseWebServ:"+responseWebServ);
				result = W83AWebServiceCall.getResultado(responseWebServ);
				W83aClsTrazas.trazaDebug(null, "===> 28 result:"+result);
		
			
			if (log.isLoggable(Level.INFO)){
				log.info("sessionToken="+sessionToken);
				//log.info("sUnsignedNotification="+sUnsignedNotification);
				//log.info("bytesNotification="+bytesFirma);
				log.info("-->" + result);
			}
			
			if (result.startsWith("Fallo")){
				result="";
			}
			
			
			return result;
			
		} catch (IOException ioe) {
			W83aClsTrazas.trazaDebug(null, "===> IOException");
			result="";
			
		} catch (Exception ex) {
			W83aClsTrazas.trazaDebug(null, "===> Exception");
			result="";
		}
		
		return result;
	}
	
	public static String comprobarFirma(String ejgvDocument) {
		String result = "";
		try {
			//DESARROLLO
			String sessionToken = W83ANotificacionThread.getTokenXLNets("w83a");
			//LOCAL
        	//String sessionToken = leerFichero("c:/config/p16b/Tokenw83a.xml", false);
			
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " **** 1 comprobarFirma", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD
			W83aClsTrazas.trazaError(null, " *******************************", new Exception() );//NOPMD

			
			if(W83AProperties.getProperty("w83a","dokusi.firma.servidor.ACTIVE").equals("true")){
				String jpdMethod = "addSignatureFooterFAC";
				W83aClsTrazas.trazaError(null, " **** 2 jpdMethod", new Exception() );//NOPMD

				MessageFactory mfactory = MessageFactory.newInstance();
				W83aClsTrazas.trazaDebug(null, " **** 5 mfactory: " + mfactory);
				SOAPMessage message = mfactory.createMessage();
				W83aClsTrazas.trazaDebug(null, " **** 6 message: " + message);
				SOAPPart soapPart = message.getSOAPPart();
				W83aClsTrazas.trazaDebug(null, " **** 7 soapPart: " + soapPart);
				SOAPEnvelope envelope = soapPart.getEnvelope();
				W83aClsTrazas.trazaDebug(null, " **** 8 envelope: " + envelope);
				SOAPBody body = envelope.getBody();
				W83aClsTrazas.trazaDebug(null, " **** 9 body: " + body);
				Name name = envelope.createName(jpdMethod, "",
						"http://www.openuri.org/");
				W83aClsTrazas.trazaDebug(null, " **** 10 name: " + name);
				SOAPBodyElement element = body.addBodyElement(name);
				W83aClsTrazas.trazaDebug(null, " **** 11 element: " + element);
				SOAPElement symbol = element.addChildElement(envelope
						.createName("sSessionToken"));
				W83aClsTrazas.trazaDebug(null, " **** 12 symbol: " + symbol);
				symbol.addTextNode(sessionToken);
				W83aClsTrazas.trazaDebug(null, " **** 13 sessionToken **** " );
				
				
				W83aClsTrazas.trazaDebug(null, " **** 13 sessionToken **** " );
				
				W83aClsTrazas.trazaDebug(null, " **** 15 " );
				symbol = element.addChildElement(envelope.createName("sEjgvDocument"));
				W83aClsTrazas.trazaDebug(null, " **** 16 symbol: " + symbol);
				symbol.addTextNode(ejgvDocument);
				
				
				W83aClsTrazas.trazaDebug(null, " **** 17 ejgvDocument **** " );
				
				W83aClsTrazas.trazaDebug(null, " **** 13 sessionToken **** " );
				
				
	
				SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
				SOAPConnection con = factory.createConnection();
				
				String url = W83AProperties.getProperty("w83a","url.ws.Q99vDigitalSignatureJWS");
				W83aClsTrazas.trazaError(null, " **** 20 url: "+url, new Exception() );//NOPMD
				if (log.isLoggable(Level.INFO)){
					log.info("sessionToken="+sessionToken);
					
					log.info("txt codigicado base64 para la firma"+ejgvDocument);
				}
				W83aClsTrazas.trazaDebug(null, " **** 21  " );
	
				SOAPMessage responseWebServ = con.call(message, url);
				W83aClsTrazas.trazaDebug(null, " **** 22 responseWebServ: "+responseWebServ );
				result = W83AWebServiceCall.getResultado(responseWebServ);
				W83aClsTrazas.trazaError(null, " **** 23 result: "+result , new Exception() );//NOPMD
				result = W83ABase64.decodeToString(result);
				if (result.startsWith("Fallo:")){
					result="";
				}
				
				System.out.println("RESULTADO:" + result);
				
				// out.close();
			}else{
				result = "Hola Mundo";
			}
			W83aClsTrazas.trazaDebug(null, " **** 25  " );
			if (log.isLoggable(Level.INFO)){
				log.info("Result obtener firma simple servidor-->" + result);
			}
			
				
			
			
			return result;
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}
	
	/**
	 * Lee un fichero y devuelve el contenido
	 * @param elFichero el nombre del fichero
	 * @param codificar indica si ha de codificarse el contenido 
	 * @return el contenido
	 */
	private static String leerFichero(String elFichero, boolean codificar){
		String cadenaSesion= "";
		try {
			File laSesion= new File(elFichero);
			
			InputStream is = new FileInputStream(laSesion);
		    
	        long length = laSesion.length();
		    
	        // Create the byte array to hold the data
	        byte[] bytes = new byte[(int) length];
		    
		    // Read in the bytes
		    int offset = 0;
		    int numRead = 0;
		    while (offset < bytes.length
		    		&& (numRead=is.read(bytes, offset, bytes.length - offset)) >= 0) {
		    	offset += numRead;
	        }

	        // Ensure all the bytes have been read in
	        if (offset < bytes.length) {
	            throw new IOException("No se ha podido leer " + elFichero);
	        }

	        // Close the input stream and return bytes
	        is.close();

	        BASE64Encoder encoder = new BASE64Encoder();

	        if (codificar) {
	            cadenaSesion = encoder.encode(bytes);
	        } else {
	            cadenaSesion = new String(bytes);
	        }

		} catch (Exception e) {
			W83aClsTrazas.trazaDebug(null, "P16BPlateaUtils.leerFichero->EXCEPTION");
		}

		return cadenaSesion;
	}
	
	private static final Logger log = Logger.getLogger(W83AEjGvDocumento.class.getName());
}
